/*global document */
var loadJavaScript;

(function () {
	"use strict";

	/**
	 * Creates a new script element.
	 * @return {Element} the script element
	 */
	function createScriptElement() {
		var script = document.createElement("script");

		script.type = "text/javascript";
		return script;
	}

	/**
	 * Appends the terminator script.
	 * @param {Element} parent
	 * @param {function} then
	 */
	function appendTerminator(parent, then) {
		var script = createScriptElement();

		loadJavaScript.then = typeof then === "function" ? then : function () {};

		script.text = "loadJavaScript.then();";
		parent.appendChild(script);
	}

	/**
	 * Loads a script.
	 * @param {Element} parent
	 * @param {string} src a path to script
	 */
	function appendScript(parent, src) {
		var script = createScriptElement();
		script.src = src;

		parent.appendChild(script);
	}

	/**
	 * Loads an array of scripts.
	 * @param {Array} scripts and array of scripts to load
	 * @param {function} then a callback function to invoke when all scripts have been loaded
	 */
	loadJavaScript = function(scripts, then) {
		var parent = document.getElementsByTagName("head")[0],
			length = scripts.length,
			i;

		for (i = 0; i < length; i++) {
			appendScript(parent, scripts[i]);
		}

		appendTerminator(parent, then);
	}
}());